-- Prefan Access Controller
-- Chat Commands

-- Variables

PAC.Commands = {}
PAC.Arguments = {}

local function AddArg( style, type, func ) table.insert( PAC.Arguments, {Style = style, Type = type, Func = func} ) end
AddArg( "PLAYER", "Player", function( nick ) return PAC.FindPlayer( nick ) end )
AddArg( "NUMBER", "number", function( num ) return tonumber( num ) end )
AddArg( "STRING", "string", function( string ) return tostring( string ) end )

-- Functions

function PAC.AddChatCommand( look, args, level, callback )
	local data = {}
	
		data.Look = "!" .. look
		data.Len = string.len( "!" .. look )
		data.Args = args
		data.Level = level
		data.Callback = callback
		
	if table.HasValue( PAC.Commands, data ) then return end
	
	table.insert( PAC.Commands, data )
	
end

function PAC.GetArgumentKey( style )

	for k,v in pairs( PAC.Arguments ) do
	
		if v.Style == style then return k end
		
	end
	
end

function PAC.ParseArguments( ply, text, args, len )

	text = string.sub( text, len )
	
	local Return = {}
	Return[1] = ply
	
	local text_args = string.Explode( " ", text )
	local args_req = string.Explode( "|", args )
	
	for k,v in pairs( args_req ) do
	
		local argkey = PAC.GetArgumentKey( v )
		
		if not argkey then PAC.Print( PAC_CONSOLE, "INVALID ARGUMENT!" ) return end
		
		local data = PAC.Arguments[argkey].Func( text_args[k] )
		
		print( k, v, argkey, text_args[k], PAC.Arguments[argkey].Type, type( data ) )
		
		if PAC.Arguments[argkey].Type != type( data ) then
		
			Return = {}
			
			PAC.Print( PAC_CHAT, ply, Color( 100, 100, 100 ), "Argument ", Color( 255, 0, 0 ), PAC.Arguments[argkey].Type, Color( 100, 100, 100 ), " is needed!  You put ", Color( 255, 0, 0 ), type( data ) )
			
			return nil
			
		else
		
			table.insert( Return, data )
			
		end
		
	end
	
	return Return
	
end

function PAC.ChatMonitor( ply, text )

	for k,v in pairs( PAC.Commands ) do
	
		text = string.lower( text )
		
		local find = string.sub( text, 1, v.Len )
			find = string.find( find, v.Look )
			
		if find then
		
			local level = PAC.GetRankNumber( v.Level )
			local ranknum = PAC.GetRankNumber( PAC.GetRank( ply ) )
		
			if ranknum <= level then
		
				local args = PAC.ParseArguments( ply, text, v.Args, v.Len + 2 )
				
				if not args then return end
				
				v.Callback( unpack( args ) )
				
			end			
			
		end
		
	end
	
end
hook.Add( "PlayerSay", "PAC_ChatMonitor", PAC.ChatMonitor )
